import process from 'process'
import * as step from '@flow-step/step-toolkit'
import { getParams } from './params'

export async function setEnv(){
    const flowJobToken: string | undefined =
        process.env['FLOW_JOB_TOKEN']
    if (flowJobToken == undefined) {
        throw new Error('missing FLOW_JOB_TOKEN')
    }

    // get RAM STS certificate
    const certificate = await step.certificate.getRamStsCertificate(flowJobToken,process.env.SERVICE_CONNECTION_ID as string)
    const params = getParams()

    if (certificate === undefined || certificate.accessKeyId === "") {
        throw new Error(`get RamStsCertificate but error: ${JSON.stringify(certificate)}`)
    }
    step.debug(`get RamStsCertificate data: ${JSON.stringify(certificate)}`)

    // set env
    step.exportEnvVar("ALICLOUD_ACCESS_KEY", certificate.accessKeyId)
    step.exportEnvVar("ALICLOUD_SECRET_KEY", certificate.accessKeySecret)
    step.exportEnvVar("ALICLOUD_STS_TOKEN", certificate.securityToken)
    step.exportEnvVar("ALICLOUD_REGION", params.regionID)
    

    return Promise.resolve(certificate)
}